<template>
  <el-select
    filterable
    v-model="userId"
    :filter-method="searchUser"
    @change="getUserId"
    v-loadmore="getMoreData"
    :placeholder="text?text:'请选择用户'" clearable>
    <el-option
      v-for="(item,index) in userOption"
      :key="index"
      :label="item.wxName + ' ' + '(' + (item.remark?item.remark+'-ID:':'ID:')+item.id + ')'"
      :value="item.id">
    </el-option>
  </el-select>
</template>

<script>
import {getListAll} from "@/api/data/user";

export default {
  // uId:用户id回显，hasOpenId：新老用户类型，text：placeholder文本提示,defaultId:默认显示的用户id
  props:['uId','hasOpenId','text','defaultId'],
  data() {
    return {
      page:1,
      limit:10,
      hasMore:true,
      userId:'',
      userOption:[],
      keyword: this.defaultId ? this.defaultId.toString() : '',
      wxName:''
    }
  },
  mounted() {
    this.getUserInfo();
  },
  methods: {
    searchUser(e){
      this.hasMore = true;
      this.page = 1;
      this.keyword = '';
      this.wxName = '';
      e%1===0 ?this.keyword = e :this.wxName = e;
      this.userOption = [];
      this.getUserInfo();
    },

    getMoreData(){
      let that = this;
      if (that.hasMore) {
        that.getUserInfo();
      }
    },

    getUserInfo(){
      let that = this;
      if(that.keyword.indexOf('.') > 0) {
        that.wxName = this.keyword;
        that.keyword = '';
      }
      let param = {
        limit:that.limit,
        page:that.page,
        hasOpenId:that.hasOpenId,
        id:that.keyword,
        wxName:that.wxName
      }
      getListAll(param).then(res=>{
        if (res) {
          that.initData(res);
        } else {
          that.hasMore = false;
        }
      }).catch((e)=>{
        that.hasMore = false;
      })
    },

    // 初始化数据
    initData(e) {
      let list = this.userOption;
      let data = e;
      list ? list = list.concat(data) : list = data;
      this.userOption = list;
      //有默认id时候回显
      if(this.defaultId) {
        this.userId = list[0].id;
      }
      this.hasMore = e.length === this.limit;
      this.page = this.page += 1;
    },

    getUserId(val){
      this.$emit('listenToUser',val?val:'');
    }
  },
  watch:{
    uId(newV,oldV){
      this.userId = this.uId;
    },
    hasOpenId(newV,oldV){

    },
  }
}
</script>

<style scoped>
.area_item span{
  font-size: 14px;
  margin-right: 10px;
}
</style>
